package com.deloitte.sapnetweaver.command
{
	
	import com.deloitte.sapnetweaver.model.ApplicationConstants;
	import com.deloitte.sapnetweaver.services.IService;
	import com.deloitte.sapnetweaver.services.ServiceController;
	import com.deloitte.sapnetweaver.view.FileUploadStatus;
	import com.deloitte.sapnetweaver.vo.FileUploadParam;
	import com.deloitte.sapnetweaver.vo.FileUploadVO;
	import com.deloitte.sapnetweaver.vo.ValueObject;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.Timer;
	
	import mx.core.Application;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	
	public class FileUploadCommand implements IService
	{		        
		private var fileUploadVO : FileUploadVO;
		private var fileParam:FileUploadParam ;
		private var winFileuploadStatus :FileUploadStatus;
		private var fileRef:FileReference = new FileReference();
        private var fileRefList:FileReferenceList = new FileReferenceList();
		public function execute(valueObject:ValueObject):void
		{
			fileUploadVO = FileUploadVO(valueObject);
			
            fileParam = new FileUploadParam();
            fileParam.STAGE = fileUploadVO.stage;
            fileParam.INDUSTRY = fileUploadVO.industry;
            fileParam.MODULE = fileUploadVO.module;
            fileParam.SUBMODULE = fileUploadVO.subModule;
            
            if(fileUploadVO.multiFileSelect == true)
            {            	
            	fileRefList.addEventListener(Event.SELECT,selectFileListHandler);
            	configureListeners(fileRefList);            		            	
            	try
				{
				    var success:Boolean = fileRefList.browse();
				}
				catch (error:Error)
				{
				    trace("Unable to browse for files.");
				}

            }   
            else
            {            		
            	fileRef.addEventListener(Event.SELECT,selectHandler);
            	configureListeners(fileRef);            		            	
            	try
				{
				    var isSuccess:Boolean = fileRef.browse();
				}
				catch (error:Error)
				{
				    trace("Unable to browse for files.");
				}	            
            }                  
            
		}
		
		private function configureListeners(dispatcher:IEventDispatcher):void 
		{
            dispatcher.addEventListener(Event.CANCEL, cancelHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
        }

        
        private function cancelHandler(event:Event):void 
        {
            trace("cancelHandler: " + event);
        }

        private function completeHandler(event:Event):void 
        {
            trace("completeHandler: " + event);
            winFileuploadStatus.statusString = "Data Uploaded SucessFully";
            if(fileUploadVO.serviceClass)
            {
            	var docPath:String = fileParam.STAGE+"/"+fileParam.INDUSTRY+"/"+fileParam.MODULE+"/"+fileParam.SUBMODULE+"/"+fileParam.FILENAME;
            	fileUploadVO.icpDocumentsVO.docPath = docPath;
            	ServiceController.getInstance().execute(fileUploadVO.serviceClass,fileUploadVO.icpDocumentsVO);
            }
            var timer:Timer = new Timer(2000);
            timer.addEventListener(TimerEvent.TIMER,timerHandler);
            timer.start();
        }
        
        private function timerHandler(event:TimerEvent):void
        {
        	Timer(event.target).stop();
        	PopUpManager.removePopUp(winFileuploadStatus);
        }
        

        private function httpStatusHandler(event:HTTPStatusEvent):void 
        {
            trace("httpStatusHandler: " + event);
        }
        
        private function ioErrorHandler(event:IOErrorEvent):void 
        {
            trace("ioErrorHandler: " + event);
        }

        private function openHandler(event:Event):void 
        {
            trace("openHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void 
        {
        	trace("progressHandler: " + event);            
            var percent:int=Math.round((event.bytesLoaded/event.bytesTotal)*100);
            winFileuploadStatus.statusString = "Loading......"+percent+ "%";            
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void 
        {
            trace("securityErrorHandler: " + event);
        }

        private function selectHandler(event:Event):void 
        {        	
        	trace("selectHandler: " + event);
        	winFileuploadStatus = FileUploadStatus( PopUpManager.createPopUp(Application.application.mainView,FileUploadStatus) );
            PopUpManager.centerPopUp(winFileuploadStatus);
            fileParam.FILENAME = fileRef.name;        	
        	doFileUpload(fileRef,fileParam);
        }
        
        
        private function selectFileListHandler(event:Event):void 
        {        	
        	trace("selectFileListHandler: " + event); 
        	winFileuploadStatus = FileUploadStatus( PopUpManager.createPopUp(Application.application.mainView,FileUploadStatus) );
            PopUpManager.centerPopUp(winFileuploadStatus);        	
        	var selectedFileArray:Array = fileRefList.fileList;
		    for (var i:uint = 0; i < selectedFileArray.length; i++)
		    {
		        fileRef = FileReference(selectedFileArray[i]);
		        fileParam.FILENAME = fileRef.name;
		        doFileUpload(fileRef,fileParam);
		    }          
        }
        
        
        private function doFileUpload(file:FileReference,parameter:Object=null):void
        {
        	file.addEventListener(Event.COMPLETE,completeHandler);
	        file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
	        file.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
	        winFileuploadStatus.fileName = file.name;
	        
	        var uploadURL:URLRequest = new URLRequest();            
            uploadURL.method = URLRequestMethod.POST;
            var url:String = ApplicationConstants.FILE_UPLOAD_URL;
            if(parameter)
            {
            	 var variables:URLVariables = new URLVariables();
            	 var properties:Array = ObjectUtil.getClassInfo(parameter).properties;
            	 var qryString:String = "";
            	 for(var i:int=0;i<properties.length;i++)
            	 {
            	 	var key:String = properties[i];
            	 	qryString = qryString+"&"+key+"="+parameter[key];
            	 }
            	 if(properties.length > 0)
            	 {
            	 	qryString = qryString.substring(1);
            	 	url = url+"?"+qryString;
            	 }
            	 
            	 /* 
            	 for(var i:int=0;i<properties.length;i++)
            	 {
            	 	var key:String = properties[i];
            	 	variables[key] = parameter[key];            	 	
            	 }
            	 variables.fpVersion = flash.system.Capabilities.version;
            	 uploadURL.data = variables; */
            	 	
            	
            }
             
             uploadURL.url = url; 
	        try
	        {	        		            
        		file.upload(uploadURL);
	        }
	        catch (error:Error)
	        {
	            trace("Unable to upload files.");
	        }
        }
    
		
	}
}